
package cn.org.seventh.web.common;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.util.Assert;

/**
 * @author <a href="mailto:ji.li@symbio-group.com">Andy</a>
 * @since Dec 20, 2007 3:59:08 PM
 */
public class DefaultMailService extends MailService implements InitializingBean {

    protected JavaMailSender mailSender;

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void send(SimpleMailMessage msg) {
        try {
            mailSender.send(msg);
        } catch (MailException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void send(SimpleMailMessage msg, String templateName, Map model) {
        // 生成html邮件内容
        String content = generateEmailContent(templateName, model);
        MimeMessage mimeMsg = null;
        try {
            mimeMsg = mailSender.createMimeMessage();
            MimeMessageHelper helper =
                new MimeMessageHelper(mimeMsg, true, "utf-8");
            helper.setTo(msg.getTo());
            helper.setSubject(msg.getSubject());
            try {
                helper.setFrom(msg.getFrom().split(" ")[1], msg.getFrom()
                    .split(" ")[0]);
            } catch (UnsupportedEncodingException e) {
                // ATODO Auto-generated catch block
                e.printStackTrace();
            }
            helper.setText(content, true);
        } catch (MessagingException ex) {
            log.error(ex.getMessage(), ex);
        }
        msg.setText(content);
        if (null != mimeMsg) {
            mailSender.send(mimeMsg);
        } else {
            mailSender.send(msg);
        }
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(mailSender, "未注入MailSender");
    }
}
